package com.yl.nettylearning.netty.day07;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author yangl
 */
public class WebSocketServer {
    public static void main(String[] args) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    //因为是基于HTTP协议，需要使用http的编码器和解码器
                    pipeline.addLast(new HttpServerCodec());
                    //以块的方式写，添加 ChunkedWriteHandler 处理器
                    pipeline.addLast(new ChunkedWriteHandler());

                    /**
                     * 1、http数据在传输过程中是分段的，HttpObjectAggregator就可以将多个分段的数据聚合
                     * 2、这就是为什么当浏览器发送大量数据时，就会发送多次请求的原因
                     */
                    pipeline.addLast(new HttpObjectAggregator(8192));
                    /**
                     * 1、对于webSocket数据，是以帧(frame)的形式传递的
                     * 2、可以看到WebSocketFrame 下面有6个子类
                     * 3、浏览器请求时，ws://localhost:2000/xxx 表示请求的uri
                     * 4、WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议，即长连接协议，保持长连接
                     * 5、通过一个状态码 101
                     * 6、浏览器端请求的地址，一定要和WebSocketServerProtocolHandler 地址一样
                     */
                    pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                    //自定义的handler，处理业务逻辑
                    pipeline.addLast(new WebSocketServerHandler());

                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(2000).sync();
            channelFuture.channel().closeFuture().sync();
        }  finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
